package com.javaweb.web.service.impl;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import jakarta.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.javaweb.base.BaseDao;
import com.javaweb.constant.CommonConstant;
import com.javaweb.enums.CamelCaseEnum;
import com.javaweb.util.core.FreemarkerUtil;
import com.javaweb.util.core.PageUtil;
import com.javaweb.util.core.StringUtil;
import com.javaweb.util.entity.Page;
import com.javaweb.util.entity.SqlConnection;
import com.javaweb.util.help.sql.BaseSql;
import com.javaweb.util.help.sql.MySqlHandle;
import com.javaweb.web.eo.dbTables.DbTablesCodeGenerateResponse;
import com.javaweb.web.eo.dbTables.DbTablesColumnListResponse;
import com.javaweb.web.eo.dbTables.DbTablesListRequest;
import com.javaweb.web.eo.dbTables.DbTablesListResponse;
import com.javaweb.web.eo.dbTables.DbTablesOperateRequest;
import com.javaweb.web.service.DbTablesService;

/**
 * 数据库表模块业务层接口实现
 * 
 * @author tank2140896
 */
@Service("dbTablesServiceImpl")
public class DbTablesServiceImpl extends BaseDao implements DbTablesService {

	/**
	 * 数据库表列表业务层接口实现
	 * 
	 * @param dbTablesListRequest 数据库表列表请求参数
	 * @return Page 分页参数
	 */
	@Override
	public Page dbTablesList(DbTablesListRequest dbTablesListRequest) {
		final String tableSchema = "test";//TODO 此处待优化
		List<DbTablesListResponse> tablelist = dbTablesDao.getTableList(tableSchema);
		if(tablelist==null||tablelist.size()<=0){
			tablelist = new ArrayList<>();
		}
		if(!StringUtil.isEmpty(dbTablesListRequest.getTableName())){
			tablelist = tablelist.stream().filter(e->e.getTableName().contains(dbTablesListRequest.getTableName())).toList();
		}
		long count = tablelist.size();
		tablelist = PageUtil.getSubList(tablelist,dbTablesListRequest.getPageSize(),dbTablesListRequest.getCurrentPage());
		Page page = new Page(dbTablesListRequest,tablelist,count);
		return page;
	}
	
	/**
	 * 获取数据库表信息业务层接口实现
	 * 
	 * @param tableName 表名
	 * @return List<DbTablesColumnListResponse> 数据库表信息列表
	 */
	@Override
	public List<DbTablesColumnListResponse> getTableColumnInfo(String tableName) {
		List<DbTablesColumnListResponse> result = new ArrayList<>();
		List<Map<String,Object>> list = dbTablesDao.getTableColumnInfo(tableName);
		for(int i=0;i<list.size();i++){
			Map<String,Object> map = list.get(i);
			DbTablesColumnListResponse dbTablesColumnListResponse = new DbTablesColumnListResponse();
			dbTablesColumnListResponse.setField(StringUtil.objectEasy2String(map.get("COLUMN_NAME")));
			dbTablesColumnListResponse.setType(StringUtil.objectEasy2String(map.get("COLUMN_TYPE")));
			dbTablesColumnListResponse.setIsNull(StringUtil.objectEasy2String(map.get("IS_NULLABLE")));
			dbTablesColumnListResponse.setComment(StringUtil.objectEasy2String(map.get("COLUMN_COMMENT")));
			dbTablesColumnListResponse.setDefaultValue(StringUtil.objectEasy2String(map.get("COLUMN_DEFAULT")));
			dbTablesColumnListResponse.setIsKey(StringUtil.objectEasy2String(map.get("COLUMN_KEY")));
			result.add(dbTablesColumnListResponse);
		}
		return result;
	}

	/**
	 * 代码生成业务层接口实现
	 * 
	 * @param tableName 表名
	 * @param httpServletResponse httpServletResponse
	 */
	@Override
	public void codeGenerate(String tableName,HttpServletResponse httpServletResponse) {
		String className = StringUtil.camelCaseConvert(tableName,CamelCaseEnum.FIRST_WORD_UPPER);
		List<DbTablesCodeGenerateResponse> result = new ArrayList<>();
		List<Map<String,Object>> list = dbTablesDao.getTableColumnInfo(tableName);
		String importOut = CommonConstant.EMPTY_VALUE;
		Map<String,String> importOutMap = new HashMap<>();
		for(int i=0;i<list.size();i++){
			Map<String,Object> map = list.get(i);
			DbTablesCodeGenerateResponse dbTablesCodeGenerateResponse = new DbTablesCodeGenerateResponse();
			dbTablesCodeGenerateResponse.setTableColumn(map.get("COLUMN_NAME").toString());//表字段名称
			dbTablesCodeGenerateResponse.setTableColumnDesc(map.get("COLUMN_COMMENT")==null?CommonConstant.EMPTY_VALUE:map.get("COLUMN_COMMENT").toString());//表字段描述
			dbTablesCodeGenerateResponse.setJavaPropertyName(StringUtil.camelCaseConvert(dbTablesCodeGenerateResponse.getTableColumn(),CamelCaseEnum.FIRST_WORD_LOWER));//java属性名称
			dbTablesCodeGenerateResponse.setKey((map.get("COLUMN_KEY")!=null&&map.get("COLUMN_KEY").equals("PRI"))?true:false);//是否主键
			String type = map.get("COLUMN_TYPE")==null?"String":String.valueOf(map.get("COLUMN_TYPE"));
			if(type.toLowerCase().contains("varchar")){
				type = "String";
			}else if(type.toLowerCase().equals("int")){
				type = "Integer";
			}else if(type.toLowerCase().equals("bigint")){
				type = "Long";
			}else if(type.toLowerCase().startsWith("date")){
				importOutMap.put("import java.util.Date;","import java.util.Date;");
				type = "Date";
			}else{
				type = "String";
			}
			dbTablesCodeGenerateResponse.setJavaType(type);//java类型
			result.add(dbTablesCodeGenerateResponse);
		}
		if(importOutMap.size()>0) {
			importOut = String.join(CommonConstant.COMMA,importOutMap.keySet());
		}
		Map<String,Object> map = new HashMap<>();
		map.put("tableName",tableName);
		map.put("className",className);
		map.put("importOut",importOut);
		map.put("propertyList",result);
		String templateFileName[] = {"po.ftl"/* ,"dao.ftl","mapper.ftl","serviceImpl.ftl","service.ftl"*/};
		try{
			ZipOutputStream zipOutputStream = new ZipOutputStream(httpServletResponse.getOutputStream());
			FreemarkerUtil.freemarkerForDbTablesCodeGenerate(map,templateFileName,tableName,zipOutputStream);
		}catch(Exception e){
			//do nothing
		}
	}

	/**
	 * 表还原业务层接口实现
	 */
	@Override
	public void dbTablesReduction() {
		try{
			String filePath = URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource("sql/init.sql").getPath(),StandardCharsets.UTF_8);
			BaseSql baseSql = new MySqlHandle();
			SqlConnection jdbcBean = new SqlConnection();
			baseSql.executeImport(jdbcBean,filePath);
		}catch(Exception e){
			//要使用此导入功能需要服务器命令行支持mysql命令
			e.printStackTrace();
		}
	}

	/**
	 * 数据库表操作业务层接口实现
	 * 
	 * @param dbTablesOperateRequest 数据库表操作请求参数
	 * @return Object 返回信息
	 */
	@Transactional
	@Override
	public Object dbTablesOperate(DbTablesOperateRequest dbTablesOperateRequest) {
		Object out = null;
		//1：查询；2：插入；3：修改；4：删除
		Integer operateType = dbTablesOperateRequest.getOperateType();
		if(operateType!=null) {
			switch(operateType) {
				case 1 -> out = commonDao.sqlSelect(dbTablesOperateRequest.getSql());
				case 2 -> out = commonDao.sqlInsert(dbTablesOperateRequest.getSql());
				case 3 -> out = commonDao.sqlUpdate(dbTablesOperateRequest.getSql());
				case 4 -> out = commonDao.sqlDelete(dbTablesOperateRequest.getSql());
			}
		}
		return out;
	}
	
}
